from datetime import datetime

from django.db import transaction
from rest_framework.viewsets import generics
from utils import response_error, response_ok
from utils.customer_modelviewset import CustomModelViewSet
from utils.exception import CustomError
from utils.permissions import IsMemberUser
from apps.member.models import MemberRecord
from apps.system.models import Upload
from apps.member.comment.models import Comment
from .filters import OptionFilter
from .models import Media
from .serializers import MediaSerializer, MediaListSerializer, MediaDetailSerializer
from ..comment.serializers import CommentSerializers


class MediaHotViewSet(generics.ListAPIView):
    queryset = Media.objects.filter(delete=False)
    serializer_class = MediaListSerializer

    def filter_queryset(self, queryset):
        f = OptionFilter(self.request.GET, queryset=queryset)
        return f.qs


class MediaDetailViewSet(generics.RetrieveAPIView):
    # 详情
    queryset = Media.objects.filter(delete=False)
    serializer_class = MediaDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()

        with transaction.atomic():
            instance.browse_count += 1
            instance.save()
            # 保存浏览记录，
            if self.request.user and self.request.user.is_authenticated:
                member_record = MemberRecord.objects.filter(content_type=Media.get_content_type(),
                                                            object_id=instance.id,
                                                            user=self.request.user,
                                                            operate=MemberRecord.BROWSE).first()
                # 同一人短时间内浏览不做记录
                if not member_record or (datetime.now() - member_record.create_time).days > 0:
                    MemberRecord.objects.create(content_object=instance, user=self.request.user,
                                                operate=MemberRecord.BROWSE, describe='浏览')
                else:
                    # 同一天，更新创建时间
                    if member_record:
                        member_record.create_time = datetime.now()
                        member_record.save()

        return super(MediaDetailViewSet, self).retrieve(request, *args, **kwargs)


class MediaViewSet(CustomModelViewSet):
    permission_classes = (IsMemberUser,)
    queryset = Media.objects.filter(delete=False)
    serializer_class = MediaSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return queryset

    def create(self, request, *args, **kwargs):
        print(request.data)
        try:
            type = request.data['type']
            name = request.data['name']
            describe = request.data['describe']
            img_id = request.data['img_id']  # 封面图
            file_id = request.data['file_id']  # 文件
            if not img_id or not file_id:
                return response_error('请上传文件!')

            banner = Upload.objects.filter(pk=img_id).first()
            file = Upload.objects.filter(pk=file_id).first()

            with transaction.atomic():

                media = Media.objects.create(type=type, name=name, describe=describe, user=request.user, banner=banner,
                                             file=file)
                MemberRecord.objects.create(content_object=media, user=self.request.user, operate=MemberRecord.INSERT,
                                            describe='上传了一部电影或者一首歌')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                diary = self.get_object()
                diary.delete = True
                diary.save()
        except Exception as e:
            return response_error(str(e))
        return response_ok()
